package com.chuangyang.fixboxmaster.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.Brand;
import com.chuangyang.fixboxmaster.bean.CostItem;
import com.chuangyang.fixboxmaster.bean.OrderPriceItem;
import com.chuangyang.fixboxmaster.bean.Part;
import com.chuangyang.fixboxmaster.bean.Specification;
import com.chuangyang.fixboxmaster.listener.PartNumChangeListener;
import com.chuangyang.fixboxmaster.ui.adapter.SelectPartListAdapter;
import com.chuangyang.fixboxmaster.ui.widgets.SelectListItem;

import java.util.ArrayList;

/**
 * Created by Administrator on 2015/7/29. 定价界面
 */
public class CompleteApplianceInfoActivity extends BaseActivity implements View.OnClickListener, PartNumChangeListener {
    private View mHeaderView;
    private View mFooterView;
    private ListView mPartListView;
    private SelectPartListAdapter mPartAdapter;
    private ArrayList<Part> mParts = new ArrayList<>();
    private SelectListItem mBrandItem;
    private SelectListItem mSpecificationItem;
    private SelectListItem mRepairTypeItem;
    private TextView mTotalPriceView;
    private TextView mCheckoutBtn;
    private TextView mNextBtn;
    private TextView mIndexView;
    private String mOrderId;
    private Brand mBrandInfo;
    private Specification mSpecification;
    private int mTranscationID;
    private String mSkillID;
    public static final int RESQUEST_CODE_BRAND = 1;
    public static final int RESQUEST_CODE_SPECIFICATION = 2;
    public static final int RESQUEST_CODE_REPAIR_TYPE = 3;
    public static final int REQUEST_CODE_ADD_PART = 4;
    public static final int TRANSCATION_ID_REPAIR = 1;
    public static final int TRANSCATION_ID_CLEAN = 2;
    public static final int TRANSCATION_ID_INSTALL = 3;
    public static final int TRANSCATION_ID_AIR = 7;
    private CostItem mSeletctItem;
    private AlertDialog mRemovePartDlg;
    private ArrayList<OrderPriceItem> mPriceList = new ArrayList<>();
    private int mTotalNum = 1;
    private int mCurrentNum = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete_appliance_info);
        mHeaderView = LayoutInflater.from(this).inflate(R.layout.part_list_header, null);
        mFooterView = LayoutInflater.from(this).inflate(R.layout.part_list_footer, null);
        Bundle bundle = getIntent().getExtras();
        mOrderId = bundle.getString("order_id");
        mTranscationID = bundle.getInt(ApplianceInfoActivity.TRANSCATION_ID);
        mSkillID = bundle.getString("skill_id");
        mTotalNum = bundle.getInt("order_num");
        initView();
    }

    private void initView() {
        mPartListView = (ListView) findViewById(R.id.add_part_list);
        mPartListView.addHeaderView(mHeaderView, null, false);
        mPartAdapter = new SelectPartListAdapter(mParts);
        mPartListView.setAdapter(mPartAdapter);
        mPartListView.addFooterView(mFooterView, null, false);

        mIndexView = (TextView) mHeaderView.findViewById(R.id.title);  // 1/1
        mIndexView.setText("" + mCurrentNum + "/" + mTotalNum);
        mBrandItem = (SelectListItem) mHeaderView.findViewById(R.id.item_brand); // 品牌
        mBrandItem.setOnClickListener(this);
        mSpecificationItem = (SelectListItem) mHeaderView.findViewById(R.id.item_format); // 规格
        mSpecificationItem.setOnClickListener(this);
        mRepairTypeItem = (SelectListItem) mHeaderView.findViewById(R.id.item_repair_type); //维修累扁
        mRepairTypeItem.setOnClickListener(this);

        TextView mAddPartView = (TextView) mFooterView.findViewById(R.id.add_part);
        mAddPartView.setOnClickListener(this);
        if ((mTranscationID == TRANSCATION_ID_CLEAN) || mTranscationID == TRANSCATION_ID_INSTALL||mTranscationID==TRANSCATION_ID_AIR) {
            mAddPartView.setVisibility(View.GONE);
        }

        mTotalPriceView = (TextView) findViewById(R.id.total_price);
        mCheckoutBtn = (TextView) findViewById(R.id.btn_checkout_imm);
        mCheckoutBtn.setOnClickListener(this);
        mNextBtn = (TextView) findViewById(R.id.btn_next);
        mNextBtn.setOnClickListener(this);
        if (mTotalNum <= 1) {
            mNextBtn.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.item_brand:
                Intent brandIntent = new Intent(this, ApplianceInfoActivity.class);
                brandIntent.putExtra(ApplianceInfoActivity.TYPE, ApplianceInfoActivity.APPLIANCE_BRAND_ACTIVITY);
                brandIntent.putExtra(ApplianceInfoActivity.ORDER_ID, mOrderId);
                startActivityForResult(brandIntent, RESQUEST_CODE_BRAND);
                //startActivity(brandIntent);
                break;
            case R.id.item_format:
                if (mBrandInfo != null) {
                    Intent specificationIntent = new Intent(this, ApplianceInfoActivity.class);
                    specificationIntent.putExtra(ApplianceInfoActivity.TYPE, ApplianceInfoActivity.APPLIANCE_SPECIFICATION_ACTIVITY);
                    specificationIntent.putExtra(ApplianceInfoActivity.BRAND_ID, "" + mBrandInfo.id);
                    specificationIntent.putExtra(ApplianceInfoActivity.SKILL_ID, "" + mSkillID);
                    startActivityForResult(specificationIntent, RESQUEST_CODE_SPECIFICATION);
                } else {
                    Toast.makeText(this, "请先选择品牌!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.item_repair_type:

                if (validateData()) {
                    Intent repairTypeIntent = new Intent(this, ModuleActivity.class);
                    repairTypeIntent.putExtra(ModuleActivity.TYPE, ModuleActivity.REPAIR_TYPE_ACTIVITY);
                    repairTypeIntent.putExtra(ApplianceInfoActivity.SPECIFICATION_ID, "" + mSpecification.specification);
                    repairTypeIntent.putExtra(ApplianceInfoActivity.TRANSCATION_ID, "" + mTranscationID);
                    repairTypeIntent.putExtra(ModuleActivity.REPAIR_TYPE, mSeletctItem);
                    repairTypeIntent.putExtra("id",mOrderId);
                    startActivityForResult(repairTypeIntent, RESQUEST_CODE_REPAIR_TYPE);
                }
                break;
            case R.id.add_part:
                if (mSeletctItem != null && mSeletctItem.type != 4) {
                    Intent partIntent = new Intent(this, ApplianceInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt(ApplianceInfoActivity.TYPE, ApplianceInfoActivity.APPLIANCE_PART_ACTIVITY);
                    bundle.putString(ApplianceInfoActivity.SPECIFICATION_ID, "" + mSpecification.specification);
                    bundle.putString(ApplianceInfoActivity.TRANSCATION_ID, "" + mTranscationID);
                    bundle.putSerializable(ApplianceInfoActivity.SELECT_PART, mParts);
                    bundle.putSerializable(ModuleActivity.REPAIR_TYPE, mSeletctItem);
                    partIntent.putExtras(bundle);
                    startActivityForResult(partIntent, REQUEST_CODE_ADD_PART);
                } else {
                    Toast.makeText(this, "请选择维修类别!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_checkout_imm:
                if (mSeletctItem != null && mSeletctItem.price > 0) {
                    addOrderPriceItem();
                    Intent costDetailIntent = new Intent(this, ModuleActivity.class);
                    costDetailIntent.putExtra(ModuleActivity.TYPE, ModuleActivity.COST_DETAIL_ACTIVITY);
                    costDetailIntent.putExtra(ModuleActivity.ORDER_ID, mOrderId);
                    //costDetailIntent.putExtra(ModuleActivity.COST_ITEM, getCostItem());
                    costDetailIntent.putExtra(ModuleActivity.ORDER_PRICE_ITEM, mPriceList);
                    startActivity(costDetailIntent);
                } else {
                    Toast.makeText(this, "请选择维修类别!", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_next:
                if (validateData()) {
                    if (mSeletctItem != null && mSeletctItem.price > 0) {
                        if (mCurrentNum < mTotalNum) {
                            addOrderPriceItem();
                            mCurrentNum++;
                            mBrandItem.setLDescription("选择品牌");
                            mSpecificationItem.setLDescription("选择规格");
                            mRepairTypeItem.setLDescription("选择维修类别");
                            mRepairTypeItem.setRDescription("");
                            mSeletctItem = null;
                            mSpecification = null;
                            mParts.clear();
                            mPartAdapter.notifyDataSetChanged();
                            mIndexView.setText("" + mCurrentNum + "/" + mTotalNum);
                        } else {
                            Toast.makeText(this, "已经是最后一个!", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(this, "请选择维修类别!", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    private boolean validateData() {
        if (mBrandInfo == null) {
            Toast.makeText(this, "请选择品牌!", Toast.LENGTH_LONG).show();
            return false;
        }
        if (mSpecification == null) {
            Toast.makeText(this, "请选择规格!", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RESQUEST_CODE_BRAND:
                if (data != null) {
                    mBrandInfo = (Brand) data.getSerializableExtra("brand");
                    if (mBrandInfo != null) {
                        if (mBrandItem.getLDescription() != null && !mBrandItem.getLDescription().equals("")) {
                            if (!mBrandItem.getLDescription().equals(mBrandInfo.title)) {
                                mSpecificationItem.setLDescription("选择规格");
                                mRepairTypeItem.setLDescription("选择维修类别");
                                mRepairTypeItem.setRDescription("");
                                mSpecification = null;
                                mParts.clear();
                                mPartAdapter.notifyDataSetChanged();
                            }
                        }
                        mBrandItem.setLDescription(mBrandInfo.title);
                    }
                }
                break;
            case RESQUEST_CODE_SPECIFICATION:
                if (data != null) {
                    mSpecification = (Specification) data.getSerializableExtra("specification");
                    if (mSpecification != null) {
                        if (mSpecificationItem.getLDescription() != null && !mSpecificationItem.getLDescription().equals("")) {
                            if (!mSpecificationItem.getLDescription().equals(mSpecification.title)) {
                                mRepairTypeItem.setLDescription("选择维修类别");
                                mRepairTypeItem.setRDescription("");
                                mParts.clear();
                                mPartAdapter.notifyDataSetChanged();
                                mSeletctItem = null;
                                setTotalPrice();
                            }
                        }
                        mSpecificationItem.setLDescription(mSpecification.title);
                    }
                }
                break;
            case RESQUEST_CODE_REPAIR_TYPE:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        CostItem item = (CostItem) bundle.getSerializable("cost_item");
                        if (item != null) {
                            if (mSeletctItem != null && mSeletctItem.type != item.type) {
                                mParts.clear();
                                mPartAdapter.notifyDataSetChanged();
                            }
                            setCurrentType(item);
                            setTotalPrice();
                        }
                    }
                }
                break;
            case REQUEST_CODE_ADD_PART:

                if (data != null) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {

                        Object object = bundle.getSerializable(ApplianceInfoActivity.SELECT_PART);
                        if (object != null) {
                            mParts = (ArrayList<Part>) object;

                            if (mParts.size() <= 0) {

                            } else {
                                Part part = getFixPrice();
                                mRepairTypeItem.setLDescription(part.title);
                                mRepairTypeItem.setRDescription("￥" + mSeletctItem.price);
                                mPartAdapter = new SelectPartListAdapter(mParts);
                                mPartListView.setAdapter(mPartAdapter);
                                mPartAdapter.setNumberChangeListener(this);
                                setTotalPrice();
                            }
                        }
                    }
                }
                break;
        }
    }

    private Part getFixPrice() {

        Part part = new Part();
        part.title = "维修费";
        part.num = 1;
        part.suggestPrice = 0;

        if (mParts != null) {
            for (Part obj : mParts) {
                if (obj.num > 0) {
                    if (obj.fixPrice > part.suggestPrice)
                        part.suggestPrice = obj.fixPrice;
                }
            }
        }
        if (part.suggestPrice <= 0) {
            part.suggestPrice = mSeletctItem.price;
        }
        mSeletctItem.price = part.suggestPrice;
        return part;
    }

    private void setCurrentType(CostItem item) {

        if (item != null) {
            if (mTranscationID == TRANSCATION_ID_REPAIR) {
                if (item.type == 4) {
                    mRepairTypeItem.setLDescription(item.title);
                } else {
                    mRepairTypeItem.setLDescription("维修费");
                }
            } else if (mTranscationID == TRANSCATION_ID_CLEAN) {
                mRepairTypeItem.setLDescription("清洗费");
            }
            mRepairTypeItem.setRDescription("￥" + item.price);
            mSeletctItem = item;
        }
    }

    @Override
    public void onChange(Part part) {
        if (part.num > 0) {
            setTotalPrice();
            mPartAdapter.notifyDataSetChanged();
        } else {
            showRemovePartDlg(part);
        }
    }

    private void showRemovePartDlg(final Part part) {

        AlertDialog.Builder cancelOrderDlg = new AlertDialog.Builder(this);
        cancelOrderDlg.setMessage("您是否要删除配件(" + part.title + ")");
        cancelOrderDlg.setCancelable(false);
        cancelOrderDlg.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                part.num = 1;
                setTotalPrice();
                mPartAdapter.notifyDataSetChanged();
            }
        });
        cancelOrderDlg.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mParts.remove(part);
                getFixPrice();
                setTotalPrice();
                mPartAdapter.notifyDataSetChanged();
            }
        });
        mRemovePartDlg = cancelOrderDlg.create();
        mRemovePartDlg.show();
    }

    private void setTotalPrice() {
        int totalPrice = 0;
        for (Part part : mParts) {
            totalPrice += part.num * part.suggestPrice;
        }
        if (mSeletctItem != null)
            totalPrice += mSeletctItem.price;
        mTotalPriceView.setText("合计: ￥" + totalPrice);
    }

    private void addOrderPriceItem() {
        OrderPriceItem item = generateOrderPriceItem();
        for (OrderPriceItem priceItem : mPriceList) {
            if (item.index == priceItem.index) {
                mPriceList.set((item.index - 1), item);
                return;
            }
        }
        mPriceList.add(item);
    }

    private OrderPriceItem generateOrderPriceItem() {
        OrderPriceItem item = new OrderPriceItem();
        item.specificationId = Integer.parseInt(mSpecification.specification);
        item.brandId = mBrandInfo.id;
        item.costitem = getCostItem();
        item.index = mCurrentNum;
        item.title = mBrandItem.getLDescription() + mSpecificationItem.getLDescription();
        return item;
    }

    private CostItem[] getCostItem() {
        ArrayList<CostItem> items = new ArrayList<>();

        if (mSeletctItem != null) {
            CostItem item = new CostItem();
            if (mTranscationID == CompleteApplianceInfoActivity.TRANSCATION_ID_REPAIR) {
                item.title = mSeletctItem.title;
                item.price = mSeletctItem.price;
                item.num = mSeletctItem.num;
                if (mSeletctItem.type == 4) {
                    item.type = 1;
                    item.partId = 0;
                } else {
                    item.title = "维修费";
                    item.type = 2;
                    item.partId = 0;
                }
            } else {
                item.price = mSeletctItem.price;
                item.num = mSeletctItem.num;
                item.title = mSeletctItem.title;
                item.type = 2;
                item.partId = 0;
            }
            items.add(item);
        }

        if (mParts != null) {
            for (Part part : mParts) {
                CostItem item = new CostItem();
                if (mSeletctItem.type == 4) {
                    item.title = mSeletctItem.title;
                    item.price = mSeletctItem.price;
                    item.num = mSeletctItem.num;
                    item.type = 1;
                    item.partId = 0;
                    items.add(item);
                } else {
                    item.title = part.title;
                    item.price = part.suggestPrice;
                    item.num = part.num;
                    if (item.num > 0) {
                        if (part.title.equals("维修费")) {
                            item.type = 2;
                            item.partId = 0;
                        } else if (part.specificationId > 0) {
                            item.type = 3;
                            item.partId = part.id;
                        } else {
                            item.type = 3;
                            item.partId = 0;

                        }
                        items.add(item);
                    }
                }
            }
        }
        CostItem[] costItems = new CostItem[items.size()];
        for (int i = 0; i < costItems.length; i++) {
            costItems[i] = items.get(i);
        }
        return costItems;
    }

}
